package objects 
{
	
	/**
	 * ...
	 * @author Tuan
	 */
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import mx.core.MovieClipLoaderAsset;
	import objects.HealthBar.HealthBar;
	import objects.MyObject;
	import starling.display.Image;
	import starling.display.MovieClip;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.core.Starling;
	import starling.textures.Texture;
	import feathers.controls.ProgressBar;
	
	public class Solider extends MyObject
	{
		private var m_move : Boolean;
		public var m_idInGroup: int;
		public var m_moveByFlag : Boolean;
		public var isTarget: Boolean;
		public var timeMove : Number;
		public var timeFinishMove : Number;
		public var m_circleColision : Image;
		
		
		private var m_moveMovie : MovieClip;
		private var m_standMovie : MovieClip;
		private var m_attackMovie : MovieClip;	
		private var m_collisionAttack:Boolean;
		private var m_range : Number;
		public var m_sprite : starling.display.Sprite;
		public var m_ringHealth : Number;
		public var m_timeHealth : Number;
		public var m_scale : Number;
		public var m_playSound :int;
       
		public function Solider(sprite : starling.display.Sprite, _pos : Point, _target :Point )
		{
			m_sprite = sprite;
			m_fullHp = Number (database.instance.RESULTSOLIDERARRAY[0]);
			m_hp = Number (database.instance.RESULTSOLIDERARRAY[0]);	
			m_hp = Number (database.instance.RESULTSOLIDERARRAY[0]);	
			m_playSound = 0;
			
			if (Number (database.instance.RESULTSOLIDERARRAY[3]) == 0)
			{
			  m_armor = Global.ARMOR_NONE;
			}
			else if (Number (database.instance.RESULTSOLIDERARRAY[3]) == 1)
			{
				m_armor = Global.ARMOR_LOW;
			}
			
			//damage, hp, heal hp
			m_ringHealth = 4;
			m_timeHealth = 0;
			m_minDamage = 1;
			m_maxDamage = 3;
			m_damage = 1; 
			m_percentDamage = 1;
			
			m_collisionAttack = false;
			m_move = false;
			m_velocity =  new Point(0, 0);
			
			m_choosedEnemy =  null;
			m_coolDown = 0;
			
			m_countAttack = 0;
			m_maxVelocity = 1.5;
			timeMove = 0;
			isTarget = false;
			m_moveByFlag = false;
			
		    m_movieVector = new Vector.<MovieClip>();
			
			m_pos = _pos;
			m_targetPos = _target;
			timeFinishMove = ccpLength(ccpSub(m_targetPos, m_pos)) / m_maxVelocity / 60;
			
			m_range = 0.5;
			m_circleColision = new Image (Assets.getTexture("circle1"));
			m_circleColision.pivotX = m_circleColision.width/2;
			m_circleColision.pivotY = m_circleColision.height / 2;
			
			m_circleColision.x = m_pos.x;
			m_circleColision.y = m_pos.y;
			m_circleColision.scaleX = m_range;
			m_circleColision.scaleY = m_range;
			
			m_circleColision.alpha = 0;
			
			m_level = 1;
		
			this.addChild (m_circleColision);
			
			this.addEventListener(Event.ADDED_TO_STAGE, init); //note
			m_sprite.addChild(this);
			
			
		}
		private function init(event :Event):void // su dung cho animation va chi animation ma thoi :v
		{
			this.removeEventListener(Event.ADDED_TO_STAGE, init);
		
			m_scale = 0.65;
		    m_animationState = Global.ENEMY_E_MOVE;
			m_newAnimationState = Global.ENEMY_E_MOVE;
			
			m_moveMovie = new MovieClip(Assets.fixgetSpriteSheet().getTextures("move_"), 8);
			m_moveMovie.pivotX =  m_moveMovie.width / 2;
		    m_moveMovie.pivotY =  m_moveMovie.height / 2;
			
			m_moveMovie.scaleX = m_scale;
			m_moveMovie.scaleY = m_scale;
			Starling.juggler.add(m_moveMovie);
			this.addChild (m_moveMovie);
			
			m_standMovie =  new MovieClip(Assets.fixgetSpriteSheet().getTextures("stand_"), 8);
			m_standMovie.pivotX =  m_standMovie.width / 2;
			m_standMovie.pivotY =  m_standMovie.height / 2;			
			m_standMovie.scaleX = m_scale;
			m_standMovie.scaleY = m_scale;
			
			
			m_attackMovie = new MovieClip(Assets.fixgetSpriteSheet().getTextures("attack_"), 8);
			m_attackMovie.pivotX =  m_attackMovie.width / 2;
			m_attackMovie.pivotY =  m_attackMovie.height / 2;			
			m_attackMovie.scaleX = m_scale;
			m_attackMovie.scaleY = m_scale;
			
			
			m_movieVector[Global.ENEMY_E_MOVE] = m_moveMovie;
			m_movieVector[Global.ENEMY_E_STAND] = m_standMovie;
			m_movieVector[Global.ENEMY_E_ATTACKED] = m_attackMovie;
			
	
			m_movieVector[m_animationState].x = m_pos.x;
			m_movieVector[m_animationState].y = m_pos.y;
			
			m_healthBarRed = new HealthBar(Assets.getSpriteSheet().getTexture("redheathbar") );
			this.addChild (m_healthBarRed);
			m_healthBarRed.x = m_pos.x - m_movieVector[m_animationState].width/2 + 10;
			m_healthBarRed.y = m_pos.y - m_movieVector[m_animationState].height + 5;
			m_healthBarRed.scaleX = m_movieVector[m_animationState].width / m_healthBarRed.mImage.width - 0.2;
			m_healthBarRed.scaleY = 0.3;
			m_healthBarRed.ratioH = 1;
			
			m_healthBar = new HealthBar(Assets.getSpriteSheet().getTexture("heathbar") );
			this.addChild (m_healthBar);
			
			m_healthBar.x = m_pos.x - m_movieVector[m_animationState].width/2 + 10;
			m_healthBar.y = m_pos.y - m_movieVector[m_animationState].height + 5;
			m_healthBar.scaleX = m_movieVector[m_animationState].width / m_healthBar.mImage.width - 0.2;
			m_healthBar.scaleY = 0.3;
			m_healthBar.ratioH = 1;
		}
		public function AttackWithNoColision ( enemy : MyObject, _target : Boolean) : void
		{
			isTarget = _target;
			enemy.m_countAttack += 1 ;
			m_choosedEnemy = enemy;
			m_choosedEnemy.m_countAttack = enemy.m_countAttack;
			m_countAttack = m_choosedEnemy.m_countAttack;
			
			if (m_choosedEnemy.m_animationState != Global.ENEMY_E_STAND)
			{
			   m_choosedEnemy.m_newAnimationState = Global.ENEMY_E_STAND;
			}
			if (m_choosedEnemy.m_movieVector[m_choosedEnemy.m_animationState].scaleX >0 )
			{
				setPositionInAttack (m_choosedEnemy, -1);
			}
			 if (m_choosedEnemy.m_movieVector[m_choosedEnemy.m_animationState].scaleX < 0)
			{
				setPositionInAttack (m_choosedEnemy, 1);
			}			
		}
		public function setPositionInAttack ( _enemy : MyObject, direction : int):void
		{
			if (_enemy.m_countAttack == 1)
				{
				   this.setTarget (new Point( _enemy.m_pos.x + direction*10, _enemy.m_pos.y));
				}
				else if (_enemy.m_countAttack == 2)
				{
				   this.setTarget (new Point( _enemy.m_pos.x + direction*10, _enemy.m_pos.y +8 ));
				}
				else if (_enemy.m_countAttack == 3)
				{
				   this.setTarget (new Point( _enemy.m_pos.x + direction*10, _enemy.m_pos.y -8 ));
				}
				else if (_enemy.m_countAttack > 3 )
				{
					this.setTarget (new Point( _enemy.m_pos.x + direction*10, _enemy.m_pos.y));
				}
		}
		public function setTarget (_target : Point) : void 
		{
			
			m_newAnimationState = Global.ENEMY_E_MOVE;
			timeMove = 0;
			m_targetPos = _target;
			timeFinishMove = ccpLength(ccpSub(m_targetPos, m_pos)) / m_maxVelocity / 60;
		}
		
		public function Move (target : Point, _t: Number, dt:Number):void
		{
			if (m_animationState == Global.ENEMY_E_MOVE)
			{
				if (m_targetPos.x < m_pos.x) {
					 this.m_movieVector[m_animationState].scaleX = m_scale;
				}
				else if (m_targetPos.x >= m_pos.x){
					 this.m_movieVector[m_animationState].scaleX = -m_scale;
				}
				timeMove += dt;
				if (timeMove >= _t) // finish move
				{
					timeMove = 0;
					if (m_choosedEnemy == null)
					{
				     	m_newAnimationState = Global.ENEMY_E_STAND;
					}
					else if (m_choosedEnemy != null)
					{
						// sau nay cho~ nay` se la cho xet' enemy vao trang thai attack
						m_newAnimationState = Global.ENEMY_E_ATTACKED;
						if (m_choosedEnemy.m_movieVector[m_choosedEnemy.m_animationState].scaleX > 0)
						{
							 this.m_movieVector[Global.ENEMY_E_ATTACKED].scaleX = -m_scale;
						}
						else if (m_choosedEnemy.m_movieVector[m_choosedEnemy.m_animationState].scaleX < 0)
			            {
						     this.m_movieVector[Global.ENEMY_E_ATTACKED].scaleX = m_scale;
						}
			
					}
					m_moveByFlag = false;
				}
				m_velocity =  ccpNormalize (ccpSub(target, m_pos));
				m_velocity = ccpMult (m_velocity, m_maxVelocity);
				m_pos =  ccpAdd ( m_pos, m_velocity);
				
			}
			m_movieVector[m_animationState].x = m_pos.x;
			m_movieVector[m_animationState].y = m_pos.y;
			
			
		}
		public function updateHealthBar () : void
		{
			if ( m_movieVector[m_animationState].scaleX > 0)
			{
			  m_healthBar.x = m_pos.x - m_movieVector[m_animationState].width/2 + 10; ;
			  m_healthBar.y = m_pos.y -  m_movieVector[m_animationState].height + 8;
			
			  m_healthBarRed.x = m_healthBar.x; 
			  m_healthBarRed.y = m_healthBar.y;
			}
			else {
			  m_healthBar.x = m_pos.x - m_movieVector[m_animationState].width/2 + 5 ; 
			  m_healthBar.y = m_pos.y -  m_movieVector[m_animationState].height + 8;
			
			  m_healthBarRed.x = m_healthBar.x; 
			  m_healthBarRed.y = m_healthBar.y;
			}
			m_healthBar.ratioH = m_hp / m_fullHp;
		}
		override public function update (dt: Number) : void
		{
			updateHealthBar();
			m_circleColision.x = m_pos.x;
			m_circleColision.y = m_pos.y;
			if( m_choosedEnemy!=null && m_choosedEnemy.m_hp <=0 ) //target chet'
			
	        {
			   m_countAttack = 0;	
			   m_newAnimationState = Global.ENEMY_E_STAND; 
		       m_choosedEnemy = null;
		       isTarget = false ;
	        }
		
			if(m_newAnimationState != m_animationState) // thay animation
			{

				removeChild(m_movieVector[m_animationState]);
				Starling.juggler.remove(m_movieVector[m_animationState]);
 				
				m_animationState = m_newAnimationState;
				addChild(m_movieVector[m_animationState]);
				Starling.juggler.add(m_movieVector[m_animationState]);		
			}
			
			Move(m_targetPos, timeFinishMove, dt); 
			
			if (m_hp > m_fullHp)
			{
				m_hp = m_fullHp;
			}
			if ( m_newAnimationState == Global.ENEMY_E_STAND)
			{
			  if (m_hp < m_fullHp)
			  {
				  m_timeHealth += dt;
				  if (m_timeHealth > 1)
				  {
					  m_timeHealth = 0;
					  m_hp += m_ringHealth;
				  }
			  }
				
			}
			
			if (m_moveByFlag == true) // KHI DANG DI CHUYEN BOI FLAG THI SE RELEASE ENEMY (neu co)
			{
				if (m_choosedEnemy != null)
				{
					m_countAttack = 0;
					isTarget = false;
					m_choosedEnemy.m_countAttack -= 1;
					m_choosedEnemy.m_newAnimationState = Global.ENEMY_E_MOVE;
					m_choosedEnemy = null;
				}
			}
			
			if (m_collisionAttack == true)
			{
				m_coolDown += dt;
				if (m_coolDown >= 0.35 ) //thoi gian nay con tuy nhe'
				{
					m_coolDown = 0;
					m_collisionAttack = false;
				}
			}
			
			if (m_animationState == Global.ENEMY_E_ATTACKED) //set attack enemy
			{
				if (m_choosedEnemy!=null && m_movieVector[m_animationState].currentFrame >= 2 &&  m_movieVector[m_animationState].currentFrame <=3 && m_collisionAttack ==false )
				{
                 if ( m_choosedEnemy != null && m_movieVector[m_animationState].bounds.intersects ( m_choosedEnemy.getRect() ) == false )
				 {
					    m_countAttack = 0;	
			            m_newAnimationState = Global.ENEMY_E_STAND; 
		                m_choosedEnemy = null;
		                isTarget = false ;
				 }
					if ( m_choosedEnemy!=null && m_movieVector[m_animationState].bounds.intersects ( m_choosedEnemy.getRect() ) )
					{
					  m_collisionAttack = true;
					  m_playSound += 1;
					  if (m_playSound == 2)
					  {
					    m_playSound = 0;	  
					    database.instance.m_Sound.playSound("Sound_Blade", 0.1);
					  }
					   if (m_choosedEnemy.m_armor == Global.ARMOR_NONE)
					   {
					       m_choosedEnemy.m_hp -= this.m_damage ;
						    
					   }
					     else if (m_choosedEnemy.m_armor == Global.ARMOR_LOW)
				         {
						   m_damage = randomRange(m_minDamage, m_maxDamage);	 
					       m_percentDamage = randomRange (1, 20);
					       this.m_damage = this.m_damage - this.m_damage * m_percentDamage / 100;
					       m_choosedEnemy.m_hp -= this.m_damage ;
						  
				         }
						 else if (m_choosedEnemy.m_armor == Global.ARMOR_MEDIUM)
				         {
						   m_damage = randomRange(m_minDamage, m_maxDamage); 
					       m_percentDamage = randomRange (21, 50);
					       this.m_damage = this.m_damage - this.m_damage * m_percentDamage / 100;
					       m_choosedEnemy.m_hp -= this.m_damage ;
						       
				         }
						 else if (m_choosedEnemy.m_armor == Global.ARMOR_HIGH)
				         {
						   m_damage = randomRange(m_minDamage, m_maxDamage); 
					       m_percentDamage = randomRange (51, 74);
					       this.m_damage = this.m_damage - this.m_damage * m_percentDamage / 100;
					       m_choosedEnemy.m_hp -= this.m_damage ;
						       
				         }
						 else if (m_choosedEnemy.m_armor == Global.ARMOR_HIGH)
				         {
						   m_damage = randomRange(m_minDamage, m_maxDamage); 
					       m_percentDamage = randomRange (75, 95);
					       this.m_damage = this.m_damage - this.m_damage * m_percentDamage / 100;
					       m_choosedEnemy.m_hp -= this.m_damage ;
						   
				         }
					   
					  
					  if (m_choosedEnemy.m_choosedEnemy == null)
					  {
						     m_choosedEnemy.m_choosedEnemy = this;
					  }
						  
					     if (m_choosedEnemy.m_animationState != Global.ENEMY_E_ATTACKED) //set cho enemy tan' cong solider
					     {
						     m_choosedEnemy.m_newAnimationState = Global.ENEMY_E_ATTACKED;
						 }
					  
					}
				}
			}
		}
		public function UpdateLevel(level : int) :void 
		{
			if (level == 2) //xu ly ca viec tang damage tang mau' tang giap o day lun
			{	   
			   m_armor = Global.ARMOR_LOW;
			   m_fullHp = database.instance.RESULTSOLIDERARRAY[1]; 	
			   m_hp = database.instance.RESULTSOLIDERARRAY[1]; 	
			   m_minDamage =  3;
			   m_maxDamage = 4;
			   
			   swapFrames (m_movieVector[Global.ENEMY_E_MOVE], Assets.fixgetSpriteSheet().getTextures("movelvOne_"));
			   swapFrames (m_movieVector[Global.ENEMY_E_ATTACKED], Assets.fixgetSpriteSheet().getTextures("attacklvOne_"));
			   swapFrames (m_movieVector[Global.ENEMY_E_STAND], Assets.fixgetSpriteSheet().getTextures("standlvOne_"));
			}
		    else if (level == 3)
			{
				m_fullHp =  database.instance.RESULTSOLIDERARRAY[2];  
				m_hp = database.instance.RESULTSOLIDERARRAY[2];  
				m_minDamage = 6;
				m_maxDamage = 10;
				if (Number( database.instance.RESULTSOLIDERARRAY[5]) == 1)
				{
					m_armor = Global.ARMOR_LOW;
				}
				else if (database.instance.RESULTSOLIDERARRAY[5] == 2)
				{
					m_armor = Global.ARMOR_MEDIUM;
				}
			   swapFrames (m_movieVector[Global.ENEMY_E_MOVE], Assets.fixgetSpriteSheet().getTextures("movelvTwo_"));
			   swapFrames (m_movieVector[Global.ENEMY_E_ATTACKED], Assets.fixgetSpriteSheet().getTextures("attacklvTwo_"));
			   swapFrames (m_movieVector[Global.ENEMY_E_STAND], Assets.fixgetSpriteSheet().getTextures("standlvTwo_"));
			}
		}
		public function swapFrames(clip:MovieClip, textures:Vector.<Texture>):void 
		{
 
	      // remove all frame but one, since a MovieClip is not allowed to have 0 frames
		  
		  

          	while(clip.numFrames > 1){
		    clip.removeFrameAt(0);
	        }
 
	         // add new frames
	          for each (var texture:Texture in textures){
		       clip.addFrame(texture);
	          }
 
	        // remove that last previous frame
           	clip.removeFrameAt(0);
 
	         // set to frame 1
	        clip.currentFrame = 1;
		  }
        
		
		override public function Collision(_enemy:MyObject, dt:Number):void
		{
			if ( m_circleColision.bounds.intersects (_enemy.getRect()) == true && m_moveByFlag == false && m_countAttack >1) // neu co doi tuong moi xuat hien va no chua co bi ai danh' ma doi' tuong hien tai bi 2 danh 1 thi 1 linh' se quay ra tieu diet ke thu
			{
				if (_enemy.m_countAttack <= 0) // neu doi tuong moi chua co ai danh la nhay vao giet lien
				{
					if (m_choosedEnemy != null) // release m_choosedenemy = cach giam m_countattack
					{
						m_choosedEnemy.m_countAttack -= 1;
						m_countAttack = 0;
						m_choosedEnemy = null;
						
					}
					AttackWithNoColision(_enemy, isTarget);
				}
			}
			if ( m_circleColision.bounds.intersects ( _enemy.getRect() ) == true && m_moveByFlag == false && isTarget == false)
			{
				isTarget = true;
				AttackWithNoColision ( _enemy, isTarget);
			}	
		}
		override public function getRect():Rectangle
		{
		      return m_movieVector [m_animationState].bounds;
		}
		override public function release() : void {
		   
		   this.removeChild (m_healthBar);
		   this.removeChild (m_healthBarRed);
		   this.removeChild(m_movieVector[m_animationState]);
		   Starling.juggler.remove(m_movieVector[m_animationState]);
		   m_movieVector = null;
		   removeChildren();
		
		  
		}
	}
}